from turtle import pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import pandas as pd
import numpy as np

# 用SSE来确定k值选取
def get_k_use_sse():
    # 读取数据
    df = pd.read_excel(r'./data/表单2/表单2-用于聚类.xlsx')
    data = df[df['玻璃类型']==1]  # 按照高钾 铅钡玻璃分类
    new_data = data.iloc[:,:-5]   # 仅挑选合适的特征

    SSE = []  # 存放每次结果的误差平方和
    # 这里k取1到8
    for k in range(1,9):
        estimator = KMeans(n_clusters=k)  # 构造聚类器
        estimator.fit(new_data)
        SSE.append(estimator.inertia_) # estimator.inertia_获取聚类准则的总和
    X = range(1,9)
    plt.xlabel('k')
    plt.ylabel('SSE')
    plt.plot(X, SSE, 'o-')
    plt.show()

# 用轮廓系数来确定k值
def get_k_use_lk():
    from sklearn.metrics import silhouette_score # 导入库

    # 读取数据
    df = pd.read_excel(r'./data/表单2/表单2-用于聚类.xlsx')
    data = df[df['玻璃类型']==1]  # 按照高钾 铅钡玻璃分类
    new_data = data.iloc[:,:-5]   # 仅挑选合适的特征

    scores = []  # 存放得分
    # 这里的k尝试取2到9
    for i in range(2, 10):
        cluster = KMeans(n_clusters=i, random_state=20).fit(new_data)
        score = silhouette_score(new_data, cluster.labels_)
        scores.append(score)

    plt.plot(range(2, 10), scores)
    plt.show()


# kmeans聚类
def kmeans():

    # 读取数据
    df = pd.read_excel(r'./data/表单2/表单2-用于聚类.xlsx')
    i = input("聚类高钾还是铅钡? 高钾按0 铅钡按1: ")  # 按照不同玻璃类别聚类

    data = df[df['玻璃类型']==int(i)]
    new_data = data.iloc[:,:-5]

    # 高钾玻璃k值取2 铅钡k值取3
    estimator = KMeans(n_clusters=(int(i)+2), random_state=10)
    estimator.fit(new_data)
    
    # print(estimator.cluster_centers_)  # 输出各个簇的中心点坐标

    # 判断表单3中的位置样本属于哪一类
    unknown_sample = np.array([51.12, 0, 0.23, 0.89, 0, 2.12, 0, 9.01, 21.24, 11.34, 1.46])
    for vec in estimator.cluster_centers_:
        dist = np.linalg.norm(unknown_sample - vec)
        print(dist)



if __name__ == '__main__':
    kmeans()